package com.vanzo.some.appinfo;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.vanzo.some.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by tisen on 2017/10/26.
 */

public class AppInfoActivity extends AppCompatActivity {

    private static final String TAG = "AppInfoActivity";
    private RecyclerView recyclerView;
    private TextView loading_tip;
    public Button output;
    private String CATEGORY_STRING = Intent.CATEGORY_DEFAULT;
    private List<AppInfo> infos = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_package);
        output = (Button) findViewById(R.id.output);
        output.setEnabled(false);
        output.setOnClickListener(outputClick);
        recyclerView = (RecyclerView) findViewById(R.id.recycle);
        loading_tip = (TextView) findViewById(R.id.loading_tip);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        handler.sendEmptyMessage(0);
    }

    private View.OnClickListener outputClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            output.setEnabled(false);
            outputHandler.sendEmptyMessage(0);
        }
    };

    private Handler outputHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            outToText();
            output.setEnabled(true);
        }
    };

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            initRecyclerView();
            output.setEnabled(true);
            outToText();
        }
    };

    private void outToText() {
        StringBuffer stringBuffer = new StringBuffer();
        int count = 0;
        stringBuffer.append(Build.MODEL + "\n");
        stringBuffer.append(Build.MANUFACTURER + "\n");
        stringBuffer.append("应用名列表：\n");
        for (AppInfo info : infos) {
            count++;
            stringBuffer.append("\t" + count + ". " + info.getLabel() + "\n")
                    .append("\t<\n")
                    .append("\t\tlauncher:packageName=\"" + info.getPackageName() + "\"\n");
            if (info.getLauncherActivityName() != null && !info.getLauncherActivityName().equals("")) {
                stringBuffer.append("\t\tlauncher:className=\"" + info.getLauncherActivityName() + "\"\n")
                        .append("\t>\n")
                        .append("\tSMARTWAKE=" + info.getPackageName() + "&" + info.getLauncherActivityName() + "\n");
            } else {
                stringBuffer.append("\t>\n");
            }
        }
        String name = "some";
        try {
//            File file = new File(getFilesDir(),name+".txt");
//            if(file.exists()){
//                file.delete();
//            }
            FileOutputStream outStream = new FileOutputStream("/sdcard/" + name + ".txt", false);
            OutputStreamWriter writer = new OutputStreamWriter(outStream, "utf-8");
            writer.write(stringBuffer.toString());
            writer.flush();
            writer.close();//记得关闭

            outStream.close();
        } catch (Exception e) {
            Log.e("m", "file write error");
        }
        String tip = "/sdcard/some.txt";
        Log.d("outToText", stringBuffer.toString());
        Toast.makeText(this, "导出至" + tip, Toast.LENGTH_LONG).show();
        Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        scanIntent.setData(Uri.fromFile(new File(tip)));
        sendBroadcast(scanIntent);
    }

    private void initRecyclerView() {
        try {
            infos = loadAppInfo(this, loading_tip);
        } catch (Exception e) {
            e.printStackTrace();
        }
        PackageAdapter adapter = new PackageAdapter(infos, this);
        recyclerView.setAdapter(adapter);
    }

    public List<AppInfo> loadAppInfo(Context context, View loading) throws Exception {
        loading.setVisibility(View.VISIBLE);
        PackageManager packageManager = context.getPackageManager();
        List<android.content.pm.PackageInfo> packageInfos = packageManager.getInstalledPackages(0);

        List<AppInfo> appInfos = new ArrayList<>();
        AppInfo appInfo = null;
        for (android.content.pm.PackageInfo packageInfo : packageInfos) {
            appInfo = new AppInfo();
            appInfo.setLabel(packageInfo.applicationInfo.loadLabel(packageManager).toString().trim());
            appInfo.setPackageName(packageInfo.packageName);
            appInfo.setVersion(packageInfo.versionName);
            appInfo.setIcon(packageInfo.applicationInfo.loadIcon(packageManager));
            appInfo.setLauncherActivityName(getLaunchActivityName(packageManager, packageInfo.packageName));
            appInfos.add(appInfo);
        }
        Collections.sort(appInfos, new AppComparator());
        System.out.println("appInfos size = " + appInfos.size() + "");
        for (AppInfo appInfo1 : appInfos) {
            System.out.println(appInfo1.toString());
        }
        loading.setVisibility(View.INVISIBLE);
        return appInfos;
    }

    private String getLaunchActivityName(PackageManager packageManager, String packageName) {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setPackage(packageName);
        List<ResolveInfo> resolveInfos = packageManager.queryIntentActivities(intent, 0);
        String mainActivityName = "";
        if (resolveInfos != null && resolveInfos.size() >= 1) {
            mainActivityName = resolveInfos.get(0).activityInfo.name;
        }
        return mainActivityName;
    }
}
